# This file is used to create a login blueprint for the flask application.
# The blueprint is used to handle the login functionality of the application.


from flask import Blueprint
from flask import request
from flask import jsonify
from settings import *
from database import SqliteSingleton
from database.user_info_table_methods import UserInfoTableMethods
from database.notification_types_table_methods import NotificationTypesTableMethods

import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

wx_blueprint = Blueprint('wx_blueprint', __name__)


@wx_blueprint.route('/get_notification_types')
def get_notification_types():
    
    # Check if the user exists in the database
    with SqliteSingleton() as conn:
        cursor = conn.cursor()
        # user_info_table_methods = UserInfoTableMethods(cursor)
        notification_types_table_methods = NotificationTypesTableMethods(conn, cursor)

        result = notification_types_table_methods.get_notification_types_by_current_status_active()

        '''[{'id': 1, 'template_code': 'SMS_467585524', 'type_name': '原水桶缺水'}, 
            {'id': 2, 'template_code': 'SMS_467430469', 'type_name': '废水箱已满'}, 
            {'id': 3, 'template_code': 'SMS_467385534', 'type_name': '最大泡次提醒'}, 
            {'id': 4, 'template_code': 'SMS_467500556', 'type_name': '滤芯快到期'}]'''

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": result
        })
    
@wx_blueprint.route('/get_user_info')
def get_user_info():

    dev_id = request.args.get('dev_id')

    if not dev_id:
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "erorrMsg": "device_id is missing",
            "resultBody": None
        })


    # Check if the user exists in the database
    with SqliteSingleton() as conn:
        cursor = conn.cursor()
        user_info_table_methods = UserInfoTableMethods(conn, cursor)

        result = user_info_table_methods.select_user_info_by_device_sn(dev_id)

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": result
        })

@wx_blueprint.route('/configure_notifications', methods=['POST'])
def configure_notifications():

    user_id = request.form.get('user_id')
    notification_types = request.form.get('notification_types')
    # notification_types : "[1,2,3,4]" 
    if not user_id or not notification_types:
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "erorrMsg": "user_id or notification_types is missing",
            "resultBody": None
        })

    # Check if the user exists in the database
    with SqliteSingleton() as conn:
        cursor = conn.cursor()
        user_info_table_methods = UserInfoTableMethods(conn, cursor)

        result = user_info_table_methods.update_user_info_notification_type_by_id(user_id, notification_types)

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": "Notification types updated successfully"
        })
    
@wx_blueprint.route('/add_user', methods=['POST'])
def add_user():

    dev_id = request.form.get('dev_id')
    name = request.form.get('name')
    phone = request.form.get('phone')
    notification_types = request.form.get('notification_types', '[]')

    if not dev_id or not name or not phone :
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "erorrMsg": "dev_id, name or phone is missing",
            "resultBody": None
        })
    
    
    if not phone.startswith('1') or len(phone) != 11 or not phone.isdigit():
        return jsonify({
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "Invalid phone number",
            "resultBody": None
        })


    # Check if the user exists in the database
    with SqliteSingleton() as conn:
        cursor = conn.cursor()
        user_info_table_methods = UserInfoTableMethods(conn, cursor)

        is_exists = user_info_table_methods.select_user_info_by_phone_and_device_sn(phone, dev_id)

        if is_exists:
            return jsonify({

                "status": 1,

                "errorCode": None,

                "erorrMsg": None,

                "resultBody": "User already exists"

            })
        
        users = user_info_table_methods.select_user_info_by_device_sn(dev_id).__len__()

        if users >= 5:
            return jsonify({    
                "status": -1,
                "errorCode": 1002,
                "erorrMsg": "Maximum number of users reached",
                "resultBody": None
            })

        user_info_table_methods.insert_user_info(name, phone, dev_id, notification_types)

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": "User added successfully"

        })
    
@wx_blueprint.route('/block_user', methods=['POST'])
def block_user_info():

    user_id = request.form.get('user_id')

    if not user_id:
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "erorrMsg": "user_id is missing",
            "resultBody": None
        })

    # Check if the user exists in the database
    with SqliteSingleton() as conn:
        cursor = conn.cursor()
        user_info_table_methods = UserInfoTableMethods(conn, cursor)

        user_info_table_methods.block_user_info(user_id)

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": "User blocked successfully"
        })
    
